#!/bin/bash

# MySQL MCP Server HTTP 模式启动脚本（增强版）

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=== MySQL MCP Server HTTP 模式启动脚本（增强版）==="

# 设置默认值
MYSQL_HOST=${MYSQL_HOST:-localhost}
MYSQL_PORT=${MYSQL_PORT:-3306}
MYSQL_USER=${MYSQL_USER:-root}
MYSQL_DATABASE=${MYSQL_DATABASE:-test}
SERVER_HOST=${SERVER_HOST:-localhost}
SERVER_PORT=${SERVER_PORT:-8080}

# HTTP服务器配置
HTTP_ENABLE_CORS=${HTTP_ENABLE_CORS:-true}
HTTP_CORS_ORIGINS=${HTTP_CORS_ORIGINS:-"*"}
HTTP_ENABLE_HEALTH_CHECK=${HTTP_ENABLE_HEALTH_CHECK:-true}
HTTP_HEALTH_CHECK_PATH=${HTTP_HEALTH_CHECK_PATH:-"/health"}
HTTP_REQUEST_TIMEOUT=${HTTP_REQUEST_TIMEOUT:-"30s"}
HTTP_ENABLE_LOGGING=${HTTP_ENABLE_LOGGING:-true}

# 数据库连接池配置
MYSQL_MAX_OPEN_CONNS=${MYSQL_MAX_OPEN_CONNS:-25}
MYSQL_MAX_IDLE_CONNS=${MYSQL_MAX_IDLE_CONNS:-25}
MYSQL_CONN_MAX_LIFETIME=${MYSQL_CONN_MAX_LIFETIME:-"5m"}
MYSQL_CONN_MAX_IDLE_TIME=${MYSQL_CONN_MAX_IDLE_TIME:-"5m"}

# 检查必需的环境变量
if [ -z "$MYSQL_USER" ]; then
    echo "错误: 请设置 MYSQL_USER 环境变量"
    echo "使用方法: MYSQL_USER=your_user MYSQL_DATABASE=your_db $0"
    exit 1
fi

if [ -z "$MYSQL_DATABASE" ]; then
    echo "错误: 请设置 MYSQL_DATABASE 环境变量"
    echo "使用方法: MYSQL_USER=your_user MYSQL_DATABASE=your_db $0"
    exit 1
fi

# 如果没有设置密码，提示用户输入
if [ -z "$MYSQL_PASSWORD" ]; then
    read -s -p "请输入 MySQL 密码: " MYSQL_PASSWORD
    echo
    export MYSQL_PASSWORD
fi

# 显示配置信息
echo
echo "=== 服务器配置 ==="
echo "服务器模式: HTTP"
echo "监听地址: $SERVER_HOST:$SERVER_PORT"
echo "MCP端点: http://$SERVER_HOST:$SERVER_PORT/mcp"

echo
echo "=== HTTP配置 ==="
echo "CORS启用: $HTTP_ENABLE_CORS"
echo "允许的源: $HTTP_CORS_ORIGINS"
echo "健康检查: $HTTP_ENABLE_HEALTH_CHECK"
echo "健康检查路径: http://$SERVER_HOST:$SERVER_PORT$HTTP_HEALTH_CHECK_PATH"
echo "请求超时: $HTTP_REQUEST_TIMEOUT"
echo "访问日志: $HTTP_ENABLE_LOGGING"

echo
echo "=== 数据库配置 ==="
echo "数据库地址: $MYSQL_HOST:$MYSQL_PORT"
echo "数据库名: $MYSQL_DATABASE"
echo "用户名: $MYSQL_USER"
echo "最大连接数: $MYSQL_MAX_OPEN_CONNS"
echo "最大空闲连接数: $MYSQL_MAX_IDLE_CONNS"
echo "连接最大生命周期: $MYSQL_CONN_MAX_LIFETIME"
echo "连接最大空闲时间: $MYSQL_CONN_MAX_IDLE_TIME"

# 设置环境变量
export SERVER_MODE=http
export SERVER_HOST
export SERVER_PORT
export MYSQL_HOST
export MYSQL_PORT
export MYSQL_USER
export MYSQL_DATABASE
export HTTP_ENABLE_CORS
export HTTP_CORS_ORIGINS
export HTTP_ENABLE_HEALTH_CHECK
export HTTP_HEALTH_CHECK_PATH
export HTTP_REQUEST_TIMEOUT
export HTTP_ENABLE_LOGGING
export MYSQL_MAX_OPEN_CONNS
export MYSQL_MAX_IDLE_CONNS
export MYSQL_CONN_MAX_LIFETIME
export MYSQL_CONN_MAX_IDLE_TIME

echo
echo "=== 启动服务器 ==="
echo "正在启动 MySQL MCP Server (HTTP模式)..."
echo

# 启动服务器
exec "$PROJECT_ROOT/bin/mysql-mcp-server" 